package com.music.mysongs.file

import android.content.Context
import java.io.*
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL
import java.util.*

class FileOP {
    fun save(cxt: Context, fileName: String, str: String): Boolean {
        var saveFlag = false
        try {
            val output = cxt.openFileOutput(fileName, Context.MODE_PRIVATE)
            val writer = BufferedWriter(OutputStreamWriter(output))
            writer.use {
                it.write(str)
            }
            saveFlag = true
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return saveFlag
    }

    fun read(cxt: Context, fileName: String): String {
        val content = StringBuilder()
        try {
            val input = cxt.openFileInput(fileName)
            val reader = BufferedReader(InputStreamReader(input))
            reader.use {
                reader.forEachLine {
                    content.append(it)
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return content.toString()
    }

    fun readNotFirstLine(cxt: Context, fileName: String): String {
        val content = StringBuffer()
        try {
            val input = cxt.openFileInput(fileName)
            val reader = BufferedReader(InputStreamReader(input))
            var firstLine: String = reader.readLine() //读取第一行数据
            reader.use {
                reader.forEachLine {
                    content.append(it)
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return content.toString()
    }

    fun readForFirstLine(cxt: Context, fileName: String): String {
        val content = StringBuilder()
        try {
            val input = cxt.openFileInput(fileName)
            val reader = BufferedReader(InputStreamReader(input))
            reader.use {
                val line: String = it.readLine() //读取第一行数据
                //   line = it.readLine()  //读取第二行数据
                content.append(line)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return content.toString()
    }
}